package cn.edu.sdju.fengguoyu;

import cn.edu.sdju.fengguoyu.proto.NewServiceMessage;
import cn.edu.sdju.fengguoyu.proto.ObserverMessageBroadcastGrpc;
import cn.edu.sdju.fengguoyu.proto.ServiceTimeoutMessage;
import io.grpc.ManagedChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.stream.Collectors;

@Component
public class HeartBeatChecker {
    Logger logger = LoggerFactory.getLogger(HeartBeatChecker.class);

    @Autowired
    ObserverConnectionsPool observerConnectionsPool;
    private boolean isAlive(RegisterServerInfo info) {
        if ((new Date().getTime()) - info.getTimestamp() >= 10000) {
            logger.info(String.format("Server:%s:%d, timeout",info.getService().getIpAddress(), info.getService().getPort()));
            for (ManagedChannel channel: observerConnectionsPool.observerChannels.values()
            ) {
                ObserverMessageBroadcastGrpc.ObserverMessageBroadcastBlockingStub stub = ObserverMessageBroadcastGrpc.newBlockingStub(channel);
                stub.sendServiceTimeout(ServiceTimeoutMessage.newBuilder().setId(info.getId()).setLastTimestamp(info.getTimestamp()).build());
            }
            return false;
        } else {
            return true;
        }
    }
    @Autowired
    RegisterServers registerServers;
    @Scheduled(fixedRate = 10000)
    public void run() {
        logger.info("Heartbeat checking");
        for (String key : registerServers.getRawData().keySet()) {
            ArrayList<RegisterServerInfo> servers = registerServers.getRawData().get(key);
            servers = servers.stream().filter(this::isAlive).collect(Collectors.toCollection(ArrayList::new));
            registerServers.getRawData().put(key, servers);
        }
    }
}
